package cn.xiongxf.system.service.impl;

import cn.xiongxf.system.domain.Role;
import cn.xiongxf.system.mapper.RoleMapper;
import cn.xiongxf.system.service.IRoleService;
import cn.xiongxf.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Transactional
    @Override
    public void del(Long id) {
        // 先删中间表
        roleMapper.removeRoleMenusByRoleId(id);
        roleMapper.removeRolePermissionsByRoleId(id);
        roleMapper.removeEmployeesRoleByRoleId(id);
        // 再删t_role
        super.del(id);
    }

    @Transactional
    @Override
    public void add(Role role) {
        super.add(role);
        // 添加角色的菜单和权限
        addRoleMenuAndPermission(role);
    }

    @Transactional
    @Override
    public void update(Role role) {
        // 更新角色表
        super.update(role);
        // 更新 = 除旧 + 迎新
        roleMapper.removeRoleMenusByRoleId(role.getId());
        roleMapper.removeEmployeesRoleByRoleId(role.getId());
        addRoleMenuAndPermission(role);
    }

    // 添加角色的菜单和权限
    private void addRoleMenuAndPermission(Role role) {
        List<Long> menus = role.getMenus();
        if (menus.size() > 0){
            roleMapper.saveRoleMenus(role);
        }
        List<Long> permissions = role.getPermissions();
        if (permissions.size() > 0){
            roleMapper.saveRolePermissions(role);
        }
    }
}
